#include <iostream>
#include "UdpServer.hpp"
#include <memory>
#include <string>
#include <vector>
using namespace std;

void Usage(string proc)
{
    cout << "\n\tUsage: " << proc << " 端口号1024+" << endl
         << endl;
}

string Interaction(const string &str)
{
    string res = "Server get a message: ";
    res += str;

    return res;
}

bool SafeCheck(const string &str)
{
    bool safe = true;

    vector<string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "yum",
        "uninstall",
        "top"};

    for (auto &e : key_word)
    {
        auto pos = str.find(e);
        if (pos != string::npos) // 找到了
        {
            safe = false;
        }
    }
    return safe;
}

string Bash(const string &str)
{
    // 命令安全检查
    if (!SafeCheck(str))
    {
        return "Banning";
    }

    FILE *fp = popen(str.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    // 读取结果
    char buffer[4096];
    string res;
    while (true)
    {
        char *ans = fgets(buffer, sizeof(buffer), fp);
        if (ans == nullptr)
        {
            break;
        }
        res += buffer;
    }
    pclose(fp);
    return res;
}

// 大写转小写
std::string UpToLow(const std::string &resquest)
{
    std::string ret(resquest);

    for (auto &rc : ret)
    {
        if (isupper(rc))
            rc += 32;
    }

    return ret;
}

int main(int argc, char *argv[])
{
    // 如果命令行参数的个数不是2，那么就要提示用户
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t port = stoi(argv[1]);

    // 创建udp服务器对象
    unique_ptr<UdpServer> svr(new UdpServer(port, "0.0.0.0"));

    // 初始化服务器
    svr->Init();

    // 启动服务器
    svr->Run(Interaction);

    return 0;
}
